import {
  pageListTruckOrders,
  approvalCancelTruckOrder,
} from "@/services/order/order_api";
import {
  CheckOutlined,
  CloseOutlined,
} from "@ant-design/icons";
import TextArea from "antd/lib/input/TextArea";
import type {
  ActionType,
  ProColumns,
} from "@ant-design/pro-components";
import {
  PageContainer,
  ProTable,
} from "@ant-design/pro-components";
import { FormattedMessage, useIntl, useModel } from "@umijs/max";
import {
  Button,
  message,
  Modal,
  Card,
  Form,
} from "antd";
import React, { useRef, useState, useEffect } from "react";
import { TruckOrderVo, TruckOrderQueryVo } from "../types";
import AddForm from "../List/components/AddForm";
import { formatToLocalTime } from '@/utils/time';
// 后端枚举映射

const TableList: React.FC = () => {
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, setCreateModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [loading, setLoading] = useState(false);
  // const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);

  // const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  // const [currentRow, setCurrentRow] = useState<TruckOrderVo>();
  // const [selectedRowsState, setSelectedRows] = useState<TruckOrderVo[]>([]);
  const [editRow, setEditRow] = useState<TruckOrderVo>();
  //  const [orderStatusEnum, setOrderStatusEnum] = useState<DictType[]>([]);
  const [tabChoice, setTabChoice] = useState<string>("ALL");
  const { initialState } = useModel("@@initialState");
  const { currentUser } = initialState || {};
  const [admin, setAdmin] = useState(currentUser?.isAdmin);
  const [form] = Form.useForm();
  const [approveVisible, setApproveVisible] = useState(false);

  const orderStatusEnum = {
    "1": {
      text: (
        <span style={{ color: "#3d6eebff", fontWeight: "bold" }}>
          <FormattedMessage
            id="pages.order.status.submitted"
            defaultMessage="submitted"
          />
        </span>
      ),
      status: "processing",
    },
    "2": {
      text: (
        <span style={{ color: "#3cb46eff", fontWeight: "bold" }}>
          <FormattedMessage
            id="pages.order.status.forecast"
            defaultMessage="forecast"
          />
        </span>
      ),
      status: "success",
    },
    "3": {
      text: (
        <span style={{ color: "#dada2aff", fontWeight: "bold" }}>
          <FormattedMessage
            id="pages.order.status.cancelling"
            defaultMessage="cancelling"
          />
        </span>
      ),
      status: "warning",
    },
    "4": {
      text: (
        <span style={{ color: "#f47608ff", fontWeight: "bold" }}>
          <FormattedMessage
            id="pages.order.status.canceled"
            defaultMessage="canceled"
          />
        </span>
      ),
      status: "default",
    },
    "11": {
      text: (
        <span style={{ color: "#ed2906ff", fontWeight: "bold" }}>
          <FormattedMessage
            id="pages.order.status.abnormal_forecast"
            defaultMessage="abnormal_forecast"
          />
        </span>
      ),
      status: "error",
    },
    "99": {
      text: (
        <span style={{ color: "#9e9e9cff", fontWeight: "bold" }}>
          <FormattedMessage
            id="pages.order.status.obsolete"
            defaultMessage="obsolete"
          />
        </span>
      ),
      status: "default",
    },
  };

  const queryPageData = async (pageParams: TruckOrderQueryVo) => {
    try {
      setLoading(true);
      const response = await pageListTruckOrders(pageParams);
      if (response.code != 0) {
        if (!response.msg) {
          throw new Error(intl.formatMessage({ id: "request.error.create" }));
        } else {
          message.error(response.msg);
        }
      }

      return response.data;
    } catch (error) {
      // console.error(error);
      // message.error(intl.formatMessage({ id: "request.error.retry" }));
      message.error(
        error.message || intl.formatMessage({ id: "request.error.default" })
      );
      return false;
    } finally {
      setLoading(false);
    }
  };

  const renderKeyValuePairs = (data: Record<string, string>) => (
    <div style={{ whiteSpace: "pre-line" }}>
      {Object.entries(data)
        .map(([key, value]) => `${key} ${value}`)
        .join("\n")}
    </div>
  );

  const columns: ProColumns<TruckOrderVo>[] = [
    {
      title: (
        <FormattedMessage
          id="pages.truckOrder.orderCode"
          defaultMessage="orderCode"
        />
      ),
      dataIndex: "orderCode",
      key: "orderCode",
      copyable: true,
      disable: true,
      width: 150,
      // ellipsis: true,
    },
    {
      title: (
        <FormattedMessage
          id="pages.truckOrder.referenceNo"
          defaultMessage="referenceNo"
        />
      ),
      dataIndex: "referenceNo",
      key: "referenceNo",
      // sorter: true,
      copyable: true,
      hideInForm: true,
      width: 150,
    },
    {
      title: (
        <FormattedMessage
          id="pages.truckOrder.trackingNumber"
          defaultMessage="trackingNumber"
        />
      ),
      dataIndex: "trackingNumber",
      key: "trackingNumber",
      // copyable: true,
      hideInForm: true,
      search: false,
      width: 150,
    },
    // {
    //   title: (
    //     <FormattedMessage
    //       id="pages.truckOrder.customerCode"
    //       defaultMessage="customerCode"
    //     />
    //   ),
    //   dataIndex: "customerCode",
    //   key: "customerCode",
    //   hideInForm: true,
    //   width: 100,
    //   ellipsis: true,
    //   search: admin && {
    //     // 控制查询表单中的顺序
    //     transform: (value) => ({ customerCode: value }),
    //     order: 1,
    //   },
    // },
    ...(admin
      ? [
          {
            title: (
              <FormattedMessage
                id="pages.truckOrder.customerCode"
                defaultMessage="customerCode"
              />
            ),
            dataIndex: "customerCode",
            key: "customerCode",
            hideInForm: true,
            width: 100,
            search: admin && {
              // 控制查询表单中的顺序
              transform: (value) => ({ customerCode: value }),
              order: 1,
            },
          },
        ]
      : []),
    {
      title: (
        <FormattedMessage
          id="pages.truckOrder.productCode"
          defaultMessage="productCode"
        />
      ),
      dataIndex: "productCode",
      key: "productCode",
      search: false,
      hideInForm: true,
      width: 100,
    },
    {
      title: (
        <FormattedMessage
          id="pages.truckOrder.spCode"
          defaultMessage="spCode"
        />
      ),
      dataIndex: "spCode",
      key: "spCode",
      search: false,
      hideInForm: true,
      width: 100,
    },
    {
      title: (
        <FormattedMessage
          id="pages.truckOrder.shippingFeeEstimate"
          defaultMessage="shippingFeeEstimate"
        />
      ),
      dataIndex: "shippingFeeEstimate",
      key: "shippingFeeEstimate",
      search: false,
      hideInForm: true,
      width: 100,
      render: (_, record) => {
        if (record.countryCode) {
          return record.shippingFeeEstimate + " " + record.countryCode;
        } else {
          return record.shippingFeeEstimate + " USD";
        }
      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.truckOrder.orderStatus"
          defaultMessage="orderStatus"
        />
      ),
      dataIndex: "orderStatus",
      key: "orderStatus",
      hideInForm: true,
      search: false,
      width: 100,
      valueType: "select",
      valueEnum: orderStatusEnum,
    },
    {
      title: (
        <FormattedMessage
          id="pages.truckOrder.pickUpCountry"
          defaultMessage="pickUpCountry"
        />
      ),
      dataIndex: "pickUpCountry",
      key: "pickUpCountry",
      hideInForm: true,
      search: false,
      width: 100,
    },
    {
      title: (
        <FormattedMessage
          id="pages.truckOrder.pickUpPostcode"
          defaultMessage="pickUpPostcode"
        />
      ),
      dataIndex: "pickUpPostcode",
      key: "pickUpPostcode",
      hideInForm: true,
      search: false,
      width: 100,
    },
    {
      title: (
        <FormattedMessage
          id="pages.truckOrder.deliveryCountry"
          defaultMessage="deliveryCountry"
        />
      ),
      dataIndex: "deliveryCountry",
      key: "deliveryCountry",
      search: false,
      hideInForm: true,
      width: 100,
    },
    {
      title: (
        <FormattedMessage
          id="pages.truckOrder.deliveryPostCode"
          defaultMessage="deliveryPostCode"
        />
      ),
      dataIndex: "deliveryPostCode",
      key: "deliveryPostCode",
      search: false,
      hideInForm: true,
      width: 100,
    },
    {
      title: (
        <FormattedMessage
          id="pages.truckOrder.createTime"
          defaultMessage="createTime"
        />
      ),
      dataIndex: "createTime",
      key: "createTime",
      search: false,
      ellipsis: true,
      render: (_, record) =>
        renderKeyValuePairs({
          [intl.formatMessage({ id: "pages.truckOrder.time.created" })]:
            record.createTime ? formatToLocalTime(record.createTime) : "-",
          [intl.formatMessage({ id: "pages.truckOrder.time.updated" })]:
            record.updateTime ? formatToLocalTime(record.updateTime) : "-",
        }),
      hideInForm: true,
      width: 230,
    },
    ...(admin
      ? [
          {
            title: (
              <FormattedMessage
                id="pages.operating"
                defaultMessage="operating"
              />
            ),
            dataIndex: "option",
            valueType: "option",
            fixed: "right",
            width: 120,
            search: false,
            disabled: true, // 修正：disable → disabled
            render: (_, record) => [
              <a
                key="view"
                onClick={async () => {
                  setEditRow(record);
                  setCreateModalOpen(true);
                }}
              >
                <FormattedMessage id="pages.view" defaultMessage="view" />
              </a>,
              <a
                key="approval"
                onClick={async () => {
                  setEditRow(record);
                  setApproveVisible(true);
                }}
              >
                <FormattedMessage
                  id="pages.approval"
                  defaultMessage="approval"
                />
              </a>,
              // <a
              //   key="reject"
              //   onClick={async () => {
              //     setEditRow(record);
              //     // setCreateModalOpen(true);
              //   }}
              // >
              //   <FormattedMessage id="pages.reject" defaultMessage="reject" />
              // </a>,
            ],
          },
        ]
      : []),
  ];

  const pageQueryCustomer = async (params, sorter, filter) => {
    // 表单搜索项会从 params 传入，传递给后端接口。
    console.log(params, sorter, filter);
    const { current, pageSize, customerCode, orderCode, referenceNo } = params;
    const queryParams: TruckOrderQueryVo = {
      current: current,
      pageSize: pageSize,
      orderStatus: 3,
    };

    if (customerCode !== undefined) queryParams.customerCode = customerCode;
    if (orderCode !== undefined) queryParams.orderCode = orderCode;
    if (referenceNo !== undefined) queryParams.referenceNo = referenceNo;

    //  console.log(searchParams)
    //  form.submit();

    console.log(queryParams);
    return await queryPageData(queryParams);
  };

const handleApprove = async (values: {
  operatorDesc: string;
  status: number;
}) => {
  try {
    await approvalCancelTruckOrder({
      orderCode: editRow?.orderCode,
      approvalStatus: values.status,
      approvalReason: values.operatorDesc,      
    });
    message.success(intl.formatMessage({ id: 'pages.payment.messages.approveSuccess' }));
    form.resetFields();
    setApproveVisible(false);
    actionRef.current?.reload();
  } catch (error) {
    message.error(intl.formatMessage({ id: 'pages.payment.messages.approveError' }));
  }
};

  return (
    <PageContainer title={false}>
      <Card
        bordered={false}
        style={{ margin: -16 }} // 消除Card与Tab之间的间距
      >
        <ProTable<TruckOrderVo, API.PageParams>
          headerTitle={intl.formatMessage({
            id: "pages.truckOrder.list",
            defaultMessage: "Order List",
          })}
          // actionRef={tabActionRefs.current[item.key]}
          actionRef={actionRef}
          loading={loading}
          // dataSource={dataSource}
          rowKey="key"
          // params={tabChoice === item.key ? searchTableParams : {}}
          // search={false}
          request={pageQueryCustomer}
          columns={columns}
          scroll={{
            x: "max-content", // 自动根据内容宽度计算
            y: 900, // 固定高度触发垂直滚动
          }}
          sticky // 表头吸顶
        />
      </Card>
      <AddForm
        // width="40%"
        visible={createModalOpen}
        values={editRow}
        onCancel={async () => {
          setCreateModalOpen(false);
        }}
        onSuccess={function (): void {
          setCreateModalOpen(false);
          setEditRow(undefined);
          // if (actionRef.current) {
          //     actionRef.current.reload();
          // }
        }}
      ></AddForm>

      <Modal
        title={intl.formatMessage({ id: "pages.truckOrder.approval.title" })}
        visible={approveVisible}
        onCancel={() => setApproveVisible(false)}
        footer={[
          <Button key="cancel" onClick={() => setApproveVisible(false)}>
            {intl.formatMessage({ id: "pages.button.cancel" })}
          </Button>,
          <Button
            key="reject"
            danger
            onClick={() => {
              form.validateFields().then((values) => {
                handleApprove({ ...values, status: 2 });
              });
            }}
          >
            <CloseOutlined />{" "}
            {intl.formatMessage({ id: "pages.payment.actions.reject" })}
          </Button>,
          <Button
            key="approve"
            type="primary"
            onClick={() => {
              form.validateFields().then((values) => {
                handleApprove({ ...values, status: 1 });
              });
            }}
          >
            <CheckOutlined />{" "}
            {intl.formatMessage({ id: "pages.payment.actions.approve" })}
          </Button>,
        ]}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="operatorDesc"
            label={intl.formatMessage({
              id: "pages.payment.modal.approvalComments",
            })}
            rules={[
              {
                required: false,
                message: intl.formatMessage({
                  id: "pages.payment.modal.approvalCommentsRequired",
                }),
              },
            ]}
          >
            <TextArea
              rows={4}
              placeholder={intl.formatMessage({
                id: "pages.payment.modal.approvalCommentsPlaceholder",
              })}
            />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default TableList;
